package com.juyu.reader.author.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.juyu.reader.author.common.Configure;
import com.juyu.reader.author.common.Constants;
import com.juyu.reader.author.common.PageDirective;
import com.juyu.reader.author.model.Author;
import com.juyu.reader.author.model.Book;
import com.juyu.reader.author.model.BookChapter;
import com.juyu.reader.author.model.Page;
import com.juyu.reader.author.service.AuthorService;
import com.juyu.reader.author.service.BookChapterService;
import com.juyu.reader.author.service.BookService;
import com.juyu.reader.author.util.Md5Util;
import com.juyu.reader.author.util.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/author")
public class AuthorController extends BaseController {

	@Autowired
	private AuthorService authorService;
	@Autowired
	private BookService bookService;
	@Autowired
	private BookChapterService bookChapterService;

	@RequestMapping("/toRegister")
	public ModelAndView toRegister(HttpServletRequest request) {

		return this.packModeAndView(request, "/register", null, null);

	}

	@RequestMapping("/toLogin")
	public ModelAndView toLogin(HttpServletRequest request) {
		Author loginAuthor = (Author) request.getSession().getAttribute(Configure.systemSessionAuthor);
		if (loginAuthor == null) {
			return this.packModeAndView(request, "/login", null, null);
		} else {
			return this.packModeAndView(request, "/index", null, null);
		}

	}

	@RequestMapping("/login")
	@ResponseBody
	public String login(Author author, HttpServletRequest request) {
		String referer = request.getHeader("Referer");
		if (StringUtil.isNullOrEmpty(referer)) {
			return null;
		}
		Author loginAuthor = new Author();
		loginAuthor.setAuthorAccount(author.getAuthorAccount());
		loginAuthor.setAuthorPassword(Md5Util.md5Encode(author.getAuthorPassword()));
		List<Author> authorList = authorService.loginAuthor(loginAuthor);

		JSONObject resultObj = new JSONObject();
		if (authorList.size() == 1) {
			Author resultAuthor = authorList.get(0);
			if (resultAuthor.getAuthorStatus() == 1) {
				request.getSession().setAttribute(Configure.systemSessionAuthor, resultAuthor);
				resultObj.put("code", 0);
				resultObj.put("url", request.getContextPath() + "/author/index");
			} else if (resultAuthor.getAuthorStatus() == -1) {
				resultObj.put("code", -2);
				resultObj.put("message", "用户帐号被禁用！");
			} else {
				resultObj.put("code", -3);
				resultObj.put("message", "登录失败，账号状态未知错误！");
			}
		} else {
			resultObj.put("code", -1);
			resultObj.put("message", "用户名或密码错误！");
		}
		return resultObj.toString();
	}

	@RequestMapping("/register")
	@ResponseBody
	public String register(Author author, HttpServletRequest request) {
		JSONObject resultObj = new JSONObject();
		List<Author> authorList = authorService.validateAuthor(author);

		if (authorList.size() >= 1) {
			resultObj.put("code", -1);
			resultObj.put("message", "该作者账号已经存在！");
			return resultObj.toString();
		}
		authorList = authorService.validateAuthorNickname(author);

		if (authorList.size() >= 1) {
			resultObj.put("code", -2);
			resultObj.put("message", "该作者笔名已经存在！");
			return resultObj.toString();
		}

		author.setAuthorPassword(Md5Util.md5Encode(author.getAuthorPassword()));
		authorService.insertAuthor(author);
		request.getSession().setAttribute(Configure.systemSessionAuthor, author);
		resultObj.put("code", 0);
		resultObj.put("url", request.getContextPath() + "/author/index");
		return resultObj.toString();
	}

	@RequestMapping("/index")
	public ModelAndView userInfo(HttpServletRequest request, Page page) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookFlag(0);
		page.setLimit(5);
		findBook.setLimit(page.getLimit());
		findBook.setPageNo(page.getPageNo());
		List<Book> bookList = bookService.findBook(findBook);
		// 设置最后章节显示
		for (Book b : bookList) {
			List<BookChapter> lastChapterList = bookChapterService.findBookChapterLastPublish(b.getBookId());
			if (lastChapterList.size() >= 1) {
				b.setBookLastChapter(lastChapterList.get(0).getChapterName());
			}
		}
		int count = bookService.countBook(findBook);
		attrMap.put("bookList", bookList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request));
		attrMap.put("sourceUrl", Constants.SOURCE_URL);
		return this.packModeAndView(request, "/index", null, attrMap);
	}

	@RequestMapping("/info")
	public ModelAndView userInfoEdit(HttpServletRequest request) {
		Author loginAuthor = (Author) request.getSession().getAttribute(Configure.systemSessionAuthor);
		Author findAuthor = new Author();
		findAuthor.setAuthorId(loginAuthor.getAuthorId());
		List<Author> authorList = authorService.findAuthor(findAuthor);
		if (authorList.size() == 1) {
			Author seAuthor = authorList.get(0);
			seAuthor.setAuthorPhone(this.hiddenAuthorInfo(seAuthor.getAuthorPhone()));
			seAuthor.setAuthorIDCard(this.hiddenAuthorInfo(seAuthor.getAuthorIDCard()));
			seAuthor.setAuthorBankNumber(this.hiddenAuthorInfo(seAuthor.getAuthorBankNumber()));
			request.getSession().setAttribute(Configure.systemSessionAuthor, seAuthor);
		}
		return this.packModeAndView(request, "/authorInfo", null, null);
	}

	private String hiddenAuthorInfo(String str) {
		if (StringUtil.isNullOrEmpty(str)) {
			return "";
		} else {
			if (str.length() > 4) {
				String tempStr = str.substring(0, str.length() - 4) + "****";
				return tempStr;
			} else {
				return str;
			}
		}
	}
	// @RequestMapping("/infoSave")
	// public ModelAndView userInfoSave(Author author, HttpServletRequest
	// request) {
	// Map<String, Object> attrMap = new HashMap<String, Object>();
	// if (StringUtil.isNullOrEmpty(author.getAuthorName()) ||
	// StringUtil.isNullOrEmpty(author.getAuthorNickname())) {
	// attrMap.put("opCode", "-2");
	// attrMap.put("opMessage", "请将用户信息填写完整！");
	// return this.packModeAndView(request, "/index", null, attrMap);
	// }
	// Author loginAuthor = (Author)
	// request.getSession().getAttribute(Configure.systemSessionAuthor);
	// Author updateAuthor = new Author();
	// updateAuthor.setAuthorName(author.getAuthorName());
	// updateAuthor.setAuthorNickname(author.getAuthorNickname());
	// updateAuthor.setAuthorId(loginAuthor.getAuthorId());
	// int updateResult = authorService.updateAuthorInfo(updateAuthor);
	//
	// if (updateResult == 1) {
	// loginAuthor.setAuthorName(author.getAuthorName());
	// loginAuthor.setAuthorNickname(author.getAuthorNickname());
	// attrMap.put("opCode", "0");
	// attrMap.put("opMessage", "用户信息保存成功！");
	// } else {
	// attrMap.put("opCode", "-1");
	// attrMap.put("opMessage", "用户信息保存失败！");
	// }
	// return this.packModeAndView(request, "/author/info", null, attrMap);
	// }

	@RequestMapping("/pwdSave")
	@ResponseBody
	public String userPasswordSave(Author author, HttpServletRequest request) {
		JSONObject resultObj = new JSONObject();

		Author sessionAuthor = this.getSessionAuthor(request);
		if (!sessionAuthor.getAuthorPassword().equals(Md5Util.md5Encode(author.getAuthorOldPassword()))) {
			resultObj.put("code", "-1");
			resultObj.put("message", "原始密码错误！");

		} else {
			Author updateAuthor = new Author();
			updateAuthor.setAuthorPassword(Md5Util.md5Encode(author.getAuthorPassword()));
			updateAuthor.setAuthorId(sessionAuthor.getAuthorId());
			authorService.updateAuthorPassword(updateAuthor);
			resultObj.put("code", "0");
			resultObj.put("url", request.getContextPath() + "/author/index");
			sessionAuthor.setAuthorPassword(updateAuthor.getAuthorPassword());
		}
		return resultObj.toString();
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute(Configure.systemSessionAuthor);
		return "redirect:/author/index";
	}

	@RequestMapping("/error")
	public ModelAndView verifyError(HttpServletRequest request) {
		return this.packModeAndView(request, "/error", "非法操作！", null);
	}
}
